<?php

namespace app\admin\controller\login;

use app\Base;
use app\service\admin\LoginServices;
use app\tools\Logs;
use app\tools\WxPlatform;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

/**
 * 微信扫码登陆
 * User : Du
 * Date : 2022/11/22
 * Time : 11:53
 * Class WxLogin
 * @package projects\controller\admin
 */
class WxLogin extends Base
{

    /**
     * 获取微信登陆二维码
     * User : Du
     * Date : 2022/11/22
     * Time : 11:50
     * @param LoginServices $services
     * @return Json
     * @throws DbException
     */
    public function WxScanCode(LoginServices $services): Json
    {
        if ($_SERVER['SERVER_ADDR'] === '127.0.0.1') {
            $this->res['data'] = [
                'id' => 1,
                'url' => 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQE27zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyQm9nNFJNX0lmSUcxdF8tUnh6MW8AAgRT-XVjAwQsAQAA'
            ];
        } else {
            $res = $services::WxScanCode($this->params);
            if (is_string($res)) {
                return $this->returnData('fail', $res);
            }
            $this->res['data'] = $res;
        }
        return $this->returnData();
    }

    /**
     * 获取扫码状态
     * User : Du
     * Date : 2022/11/22
     * Time : 11:50
     * @param LoginServices $services
     * @return Json
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCodeStatus(LoginServices $services): Json
    {
        $res = $services::ScanCodeStatus($this->params);
        if (!$res) {
            return $this->returnData('fail', '无效请求');
        }
        $this->res['data'] = $res;
        return $this->returnData();
    }

    /**
     * 微信公众号服务器认证
     * User : Du
     * Date : 2022/11/22
     * Time : 11:50
     * @param WxPlatform $wxPlatform
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function certification(WxPlatform $wxPlatform): void
    {
//        /* 服务器验证验证后删除即可 */
//        $signature = $this->params['signature'];
//        $timestamp = $this->params['timestamp'];
//        $nonce = $this->params['nonce'];
//
//        $token = 'du1760';  //自定义加密token
//        $tmpArr = [$token, $timestamp, $nonce];
//        sort($tmpArr, SORT_STRING);
//        $tmpStr = implode($tmpArr);
//        $tmpStr = sha1($tmpStr);
//
//        if ($tmpStr == $signature) {
//            echo $this->params['echostr'];
//        } else {
//            echo 'false';
//        }
//        exit;

        //捕获微信消息回调XML数据
        $data = file_get_contents("php://input");
        $data = (array)simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        Logs::info('微信回复测试', ['data' => $data], '微信通知1');
        if (isset($data['Ticket'])) {
            //扫码登陆处理
            $wxPlatform::getBingUser($data);
        }
        $this->responseMsg($data);
    }

    /**
     * 消息回复（关键词自动回复在此修改）
     * User : Du
     * Date : 2022/11/22
     * Time : 11:51
     * @param array $data
     */
    public function responseMsg(array $data)
    {
        $fromUsername = $data['FromUserName'];
        $toUsername = $data['ToUserName'];
        $keyWord = $data['Content'] ?? '';  //关键词
        $time = time();
        $textTpl = "<xml>
              <ToUserName><![CDATA[%s]]> </ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[%s]]></MsgType>
              <Content><![CDATA[%s]]></Content>
              <FuncFlag>0</FuncFlag>
              </xml>";
        $msgType = "text";
        if (!$keyWord) {
            switch ($data['Event']) {
                case "SUBSCRIBE";
                    $content = "感谢您的关注！";
                    break;
                case "SCAN";
                    $content = "扫码成功";
                    break;
                default;
                    $content = "欢迎光临!";
            }
        } else {
            $content = '暂无相关文档';
        }

        if ($content) {
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $content);
            echo $resultStr;
        }
    }
}